<template>
  <a-modal
    width="52.0833vw"
    v-model:open="visible"
    @cancel="close"
    :footer="null"
    :closable="false"
    :maskClosable="!submiting"
  >
    <div class="part-six-content">
      <div class="title">
        {{
          isAdd ? $t("form.part_six.add_title") : $t("form.part_six.edit_title")
        }}
      </div>
      <a-form ref="formRef" :model="formData" id="part-six-dialog">
        <a-form-item
          :label="$t('form.part_six.form.item_1.label')"
          name="date"
          :rules="[
            {
              required: true,
              message: 'Date is required!',
              trigger: 'blur',
            },
          ]"
        >
          <a-date-picker v-model:value="formData.date">
            <template #suffixIcon> </template>
          </a-date-picker>
        </a-form-item>
        <a-form-item
          :label="$t('form.part_six.form.item_2.label')"
          name="type"
          :rules="[
            {
              required: true,
              message: 'Model is required!',
              trigger: 'blur',
            },
          ]"
        >
          <a-select v-model:value="formData.type" @change="airModelChange">
            <a-select-option
              v-for="item in globalStore.airModelList"
              :key="item.title"
              :value="item.title"
              >{{ item.title }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item
          :label="$t('form.part_six.form.item_3.label')"
          name="family_id"
          :rules="[
            {
              required: true,
              validator: validateFamily,
              trigger: 'blur',
            },
          ]"
        >
          <a-select
            v-model:value="formData.family_title"
            :disabled="familyList.length == 0"
            @change="FamilySelectChange"
          >
            <a-select-option
              v-for="item in familyList"
              :key="item.title"
              :value="item.title"
              >{{ item.title }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item
          :label="$t('form.part_six.form.item_4.label')"
          name="ata"
          :rules="[
            {
              required: true,
              message: 'ATA is required!',
              trigger: 'blur',
            },
          ]"
        >
          <a-select v-model:value="formData.ata" @change="ataChange">
            <a-select-option
              v-for="item in globalStore.ataList"
              :key="item.no"
              :value="item.no"
              >{{ item.no }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <a-form-item
          :label="$t('form.part_six.form.item_5.label')"
          name="engine_title"
          :rules="[
            {
              required: true,
              validator: validateEngine,
              trigger: 'blur',
            },
          ]"
        >
          <a-select
            v-model:value="formData.engine_title"
            :disabled="engineList.length == 0"
          >
            <a-select-option
              v-for="item in engineList"
              :key="item.title"
              :value="item.title"
              >{{ item.title }}</a-select-option
            >
          </a-select>
        </a-form-item>
        <!-- <a-form-item></a-form-item> -->
        <a-form-item
          :label="$t('form.part_six.form.item_6.label')"
          name="ac"
          :rules="[
            {
              required: true,
              message: 'AC is required!',
              trigger: 'blur',
            },
          ]"
        >
          <a-input :maxlength="50" v-model:value.trim="formData.ac"></a-input>
        </a-form-item>
        <a-form-item
          :label="$t('form.part_six.form.item_7.label')"
          name="timespent"
          :rules="[
            {
              required: true,
              message: 'timespent is required!',
              trigger: 'blur',
            },
          ]"
        >
          <a-input :maxlength="50" v-model:value="formData.timespent"></a-input>
        </a-form-item>
        <a-form-item
          :label="$t('form.part_six.form.item_8.label')"
          name="subject"
          :rules="[
            {
              required: true,
              validator: validateSubject,
              trigger: 'blur',
            },
          ]"
        >
          <div class="subject-inner">
            <a-textarea
              v-if="formData.is_select == 2"
              v-model:value.trim="formData.subject"
              :maxlength="1000"
              :autoSize="{ minRows: 6, maxRows: 6 }"
            ></a-textarea>
            <a-select v-else v-model:value="formData.subject">
              <a-select-option
                v-for="item in subjectList"
                :key="item.id"
                :value="item.title"
                >{{ item.title }}</a-select-option
              >
            </a-select>
            <a-button type="primary" @click="toggleSubjectInput">{{
              formData.is_select == 2
                ? $t("btnText.option")
                : $t("btnText.custom")
            }}</a-button>
          </div>
        </a-form-item>
        <a-form-item :label="$t('form.part_six.form.item_9.label')">
          <div class="label-list">
            <div
              class="label-item"
              :class="item.checked ? 'active' : ''"
              @click="setLabelItem(item, 'action')"
              v-for="(item, index) in actionList"
              :key="index"
            >
              {{ item.label }}
            </div>
          </div>
        </a-form-item>
        <a-form-item :label="$t('form.part_six.form.item_10.label')">
          <div class="label-list">
            <div
              class="label-item"
              :class="item.checked ? 'active' : ''"
              @click="setLabelItem(item, 'function')"
              v-for="(item, index) in functionList"
              :key="index"
            >
              {{ item.label }}
            </div>
          </div>
        </a-form-item>
      </a-form>
      <div class="footer-btns">
        <a-button
          type="primary"
          :loading="submiting"
          @click="submit"
          class="green"
          >{{ $t("btnText.save_info") }}</a-button
        >
        <a-button danger type="primary" @click="close">{{
          $t("btnText.close")
        }}</a-button>
      </div>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, getCurrentInstance, nextTick, ref } from "vue";
import type { PartSixData, SubjectItem } from "../../types/part";
import { useGlobalStore, useMemberStore } from "../../store";
import {
  postPartSixDataCreate,
  postPartSixDataUpdate,
  postPartSixSubjectList,
  postPartSixSelectFamily,
  postPartSixEngineAll,
} from "../../api/part";
import { message } from "ant-design-vue";
import { useDateFormat } from "@vueuse/core";

import dayjs from "dayjs";
import type { EngineItem } from "../../types/global";
const globalStore = useGlobalStore();
const memberStore = useMemberStore();
const props = defineProps<{
  isAdd: boolean;
  data: PartSixData;
}>();

const formData = ref({
  date: "",
  type: "",
  type_id: "",
  ac: "",
  ata: "",
  ata_id: "",
  subject: "",
  timespent: "",
  sgh: "0",
  ri: "0",
  ts: "0",
  fot: "0",
  isp: "0",
  mp: "0",
  family_id: "",
  family_title: "",
  engine_title: "",
  engine_id: "",
  execution_person: "0",
  supervisor: "0",
  crs: "0",
  is_select: 1,
});

const actionList = ref([
  {
    label: "SGH",
    key: "sgh",
  },
  {
    label: "R/I",
    key: "ri",
  },
  {
    label: "TS",
    key: "ts",
  },
  {
    label: "FOT",
    key: "fot",
  },
  {
    label: "ISP",
    key: "isp",
  },
  {
    label: "MP",
    key: "mp",
  },
]);

const functionList = ref([
  {
    label: "Execution Person",
    key: "execution_person",
  },
  {
    label: "Supervisor",
    key: "supervisor",
  },
  {
    label: "CRS",
    key: "crs",
  },
]);

const validateFamily = (_rule: any, value: string) => {
  if (familyList.value.length == 0) {
    if (!formData.value.type_id)
      return Promise.reject("Please Select Model First!");
    return Promise.resolve();
  } else {
    if (!value && familyList.value.length > 0) {
      return Promise.reject("Family is required!");
    } else {
      return Promise.resolve();
    }
  }
};

const validateEngine = (_rule: any, value: string) => {
  if (engineList.value.length == 0) {
    if (!formData.value.family_id)
      return Promise.reject("Please Select Family First!");
    return Promise.resolve();
  } else {
    if (!value && familyList.value.length > 0) {
      return Promise.reject("Engine is required!");
    } else {
      return Promise.resolve();
    }
  }
};
const validateSubject = (_rule: any, value: string) => {
  if (engineList.value.length == 0) {
    if (!formData.value.family_id && !formData.value.ata)
      return Promise.reject("Please Select Family And ATA First!");
    return Promise.resolve();
  } else {
    if (!value && familyList.value.length > 0) {
      return Promise.reject("Subject is required!");
    } else {
      return Promise.resolve();
    }
  }
};

const getEngineId = (title: string) => {
  let id = "";
  engineList.value!.forEach((item) => {
    if (item.title == title) {
      id = item.id + "";
    }
  });
  return id;
};

const subjectList = ref<SubjectItem[]>([]);
const getSubjectData = async () => {
  if (formData.value.is_select != 1) return;
  let family_id = formData.value.family_id;
  let ata_id = formData.value.ata_id;
  if (family_id && ata_id) {
    let res = await postPartSixSubjectList(family_id, ata_id);
    if (res.code == 200) {
      subjectList.value = res.data;
    }
  }
};

const familyList = ref<any[]>([]);
const getSelectFamilyData = async () => {
  let type_id = formData.value.type_id;
  if (type_id) {
    let res = await postPartSixSelectFamily(type_id);
    if (res.code == 200) {
      familyList.value = res.data || [];
      if (props.data) {
        FamilySelectChange(formData.value.family_title);
      }
    }
  }
};

const airModelChange = () => {
  formData.value.engine_title = "";
  formData.value.type_id = globalStore.getTypeIdByTypeTitle(
    formData.value.type!
  );
  familyList.value = [];
  engineList.value = [];
  formData.value.engine_id = "";
  formData.value.family_title = "";
  getSubjectData();
  getSelectFamilyData();
};

const ataChange = () => {
  formData.value.ata_id = globalStore.getAtaIdByAtaTitle(formData.value.ata!);
  getSubjectData();
};

const setLabelItem = (item, key: string) => {
  setAllChecked(key);
  if (item.checked) {
    item.checked = false;
    formData.value[item.key] = "0";
  } else {
    item.checked = true;
    formData.value[item.key] = "1";
  }
};

const setAllChecked = (key: string) => {
  if (key == "action") {
    actionList.value.forEach((item) => {
      item.checked = false;
      formData.value[item.key] = "0";
    });
  }
  if (key == "function") {
    functionList.value.forEach((item) => {
      item.checked = false;
      formData.value[item.key] = "0";
    });
  }
};

const engineList = ref<any[]>([]);
const FamilySelectChange = async (title) => {
  let sel_item = familyList.value.find((item) => item.title == title);
  formData.value.family_id = sel_item.id;
  let engine_ids = sel_item.engine_ids;
  let res = await postPartSixEngineAll(engine_ids);
  engineList.value = res.data;
};

const visible = ref(false);
const formRef = ref();

const toggleSubjectInput = () => {
  formData.value.is_select == 1
    ? (formData.value.is_select = 2)
    : (formData.value.is_select = 1);
  getSubjectData();
};

const show = () => {
  visible.value = true;
  formData.value.member_id = memberStore.profile?.id + "";
  // 初始值赋值
  if (props.data) {
    formData.value.id = props.data.id;
    let dateSplit = props.data.date.split("/");
    let date = [dateSplit[2], dateSplit[1], dateSplit[0]].join("-");
    formData.value.date = formatDate(date);
    formData.value.type_id = props.data.type_id;
    formData.value.type = props.data.type;
    formData.value.timespent = props.data.timespent;
    formData.value.subject = props.data.subject;
    formData.value.ac = props.data.ac;
    formData.value.ata_id = props.data.ata_id!;
    formData.value.ata = props.data.ata;
    formData.value.subject = props.data.subject;
    formData.value.engine_title = props.data.engine_title!;
    formData.value.engine_id = props.data.engine_id!;
    formData.value.is_select = props.data.is_select!;
    formData.value.family_title = props.data.family_title!;
    formData.value.family_id = props.data.family_id;
    initCheckedBox();
    getSubjectData();
    getSelectFamilyData();
  }
  nextTick(() => {
    initLabel();
  });
};

const initCheckedBox = () => {
  Object.keys(props.data).forEach((key) => {
    if (props.data[key] == "1") {
      formData.value[key] = "1";
      actionList.value.forEach((item) => {
        if (item.key === key) {
          item.checked = true;
        }
      });
      functionList.value.forEach((item) => {
        if (item.key === key) {
          item.checked = true;
        }
      });
    }
  });
};

const initLabel = () => {
  let dom = document
    .querySelector("#part-six-dialog")
    ?.querySelectorAll(".ant-form-item")[6]!;
  let labelText = dom?.querySelector(".ant-form-item-label label")?.innerHTML;
  dom.querySelector(".ant-form-item-label label")!.innerHTML =
    labelText!.replace(" ", "<br/>");
};

const $t = getCurrentInstance()?.appContext.config.globalProperties.$t;

const emits = defineEmits(["complete"]);
const submiting = ref(false);
const submit = () => {
  formRef.value.validate().then(async () => {
    formData.value.engine_id =
      getEngineId(formData.value.engine_title!) || props.data.engine_id!;
    formData.value.ata_id = globalStore.getAtaIdByAtaTitle(formData.value.ata!);
    formData.value.type_id = globalStore.getTypeIdByTypeTitle(
      formData.value.type!
    );
    let obj = {
      date: dayjs(formData.value.date).format("YYYY-MM-DD"),
    };
    let params = JSON.parse(JSON.stringify(formData.value));
    Object.assign(params, obj);
    submiting.value = true;
    if (props.isAdd) {
      let res = await postPartSixDataCreate(params);
      if (res.code === 200) {
        message.success($t("message.success.add"));
        close();
        emits("complete");
      } else {
        message.error($t("message.error.add"));
        close();
      }
    } else {
      let res = await postPartSixDataUpdate(params);
      if (res.code === 200) {
        message.success($t("message.success.update"));
        close();
        emits("complete");
      } else {
        message.error($t("message.error.update"));
        close();
      }
    }
    submiting.value = false;
  });
};

const close = () => {
  visible.value = false;
  // 关闭弹窗时清空数据
  formData.value = {
    date: "",
    type: "",
    type_id: "",
    ac: "",
    ata: "",
    ata_id: "",
    subject: "",
    timespent: "",
    sgh: "0",
    ri: "0",
    ts: "0",
    fot: "0",
    isp: "0",
    mp: "0",
    family_id: "",
    family_title: "",
    engine_title: "",
    engine_id: "",
    execution_person: "0",
    supervisor: "0",
    crs: "0",
    is_select: 1,
  };
  // 清空选项
  familyList.value = [];
  subjectList.value = [];
  actionList.value.map((item) => {
    item.checked = false;
  });
  functionList.value.map((item) => {
    item.checked = false;
  });
};

defineExpose({
  show,
  close,
});
</script>
<style scoped lang="less">
.subject-inner {
  display: flex;
  width: 100%;
  gap: 10px;
  .ant-select {
    flex: 1;
    width: 80%;
  }
  .ant-btn {
    height: 40px !important;
  }
}
.part-six-content {
  .title {
    padding-top: 15px;
    padding-bottom: 40px;
    text-align: center;
    font-size: 22px;
  }
  :deep(.ant-form) {
    display: grid;
    grid-template-columns: 1fr 1fr;
    column-gap: 10px;
    .ant-form-item-label {
      width: 110px;
      justify-content: center;
      align-items: flex-start;
      label {
        margin-right: 10px;
        text-align: center;
        &::after,
        &::before {
          display: none;
        }
      }
    }
    .ant-form-item {
      &:nth-child(9),
      &:nth-child(8),
      &:nth-child(7) {
        grid-column: 1 / span 2;
      }
    }

    .label-list {
      display: flex;
      flex-wrap: wrap;
      font-size: 15px;
      align-items: center;
      gap: 10px;
      .label-item {
        padding: 4px 10px;
        cursor: pointer;
        border-radius: 8px;
        border: 1px solid #ccc;
        &.active {
          background-color: #05204b;
          border-color: transparent;
          color: #fff;
        }
      }
    }
  }
  .footer-btns {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 25px;
    gap: 30px;
    .ant-btn {
      &.green {
        background-color: #006600;
      }
      &.ant-btn-dangerous {
        background-color: #f00;
      }
    }
  }
}
</style>
